package com.heima.comment.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    UserFeign userFeign;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //评论id不能为空  TODO 注解
        // size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate    limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()));
        //创建时间 降序
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        query.limit(dto.getSize());
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(list);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        List<ApCommentRepayVO> vos = new ArrayList<>();
        //遍历 当前回复列表，将每一个回复信息 封装成 vo
        for (ApCommentRepay repay : list) {
            // 点赞数据存入
            ApCommentRepayVO repayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(repay, repayVO);
            //基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
            Query query1 = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(repay.getId())
                    .and("operation").is((short) 0)
            );
            ApCommentRepayLike one = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
            if (one != null) {
                //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
                repayVO.setOperation((short) 0);
            }
            vos.add(repayVO);
        }
        ResponseResult result = ResponseResult.okResult(vos);
        result.setHost(webSite);
        return result;
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        if (dto.getCommentId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符 注解 TODO
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //回复内容安全校验
        //简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = map.get("suggestion").toString();
            if (suggestion.equals("block")) {
                String minganci = map.get("minganci").toString();
                System.out.println("==============");
                String[] split = minganci.split("_hmtt_");
                for (int i = 1; i < split.length; i++) {
                    String[] split1 = split[i].split("~");
                    System.out.println(split1);
                    dto.setContent(dto.getContent().replace(split1[0], "**"));
                    System.out.println("===========");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"服务器繁忙");
        }

        //2. 根据评论id查询评论信息  检查是否存在
        ApComment byId = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (byId == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 保存评论回复信息
        ApCommentRepay repay = new ApCommentRepay();
        repay.setAuthorId(user.getId());
        // 远程调用作者信息
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        // 封装数据
        ApUser data = result.getData();

        repay.setAuthorName(data.getName());
        repay.setCommentId(dto.getCommentId());
        repay.setContent(dto.getContent());
        repay.setLikes(0);
        repay.setCreatedTime(new Date());
        repay.setUpdatedTime(new Date());
        mongoTemplate.insert(repay);

        //4. 修改评论信息中回复数量 + 1
        byId.setReply(byId.getReply() + 1);
        mongoTemplate.save(byId);
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //回复id不能为空  TODO注解   operation 必须 0 或 1

        //校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验回复信息是否存在
        ApCommentRepay byId = mongoTemplate.findById(dto.getCommentReppayId(), ApCommentRepay.class);
        if (byId == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "回复信息不存在");
        }
        //2. 如果是点赞  判断是否点过赞
        Map map = new HashMap<>();
        if (dto.getOperation() == 0) {
            //点过赞提示请勿重复点赞
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(byId.getId())
                    .and("operation").is((short) 0));
            ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
            if(one!=null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"已经关注过了");
            }
            //未点过赞， 保存点赞信息
            ApCommentRepayLike like = new ApCommentRepayLike();
            like.setAuthorId(user.getId());
            like.setCommentRepayId(byId.getId());
            like.setOperation((short)0);
            mongoTemplate.insert(like);
            //并将回复信息的点赞数量字段+1
            byId.setLikes(byId.getLikes()+1);
            //并将回复信息的点赞数量字段
            mongoTemplate.save(byId);
            mongoTemplate.save(byId);
            map.put("likes",byId.getLikes());

        }else {
            //3. 如果是取消赞
            //  删除点赞信息
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(byId.getId())
                    .and("operation").is((short) 0));
            mongoTemplate.remove(query,ApCommentRepayLike.class);
            //删除点赞信息
            byId.setLikes(byId.getLikes()-1);
            if(byId.getLikes()<0){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"操作有误");
            }
            mongoTemplate.save(byId);
            //并将回复信息的点赞数量字段
            map.put("likes",byId.getLikes());

        }
        //4. 返回当前回复的最新点赞数量      数据的key:  likes

        NewBehaviorDTO behaviorDTO = new NewBehaviorDTO();
        behaviorDTO.setType(NewBehaviorDTO.UpdateArticleType.COMMENT);
        behaviorDTO.setArticleId(Long.valueOf(byId.getAuthorId()));
        behaviorDTO.setAdd(dto.getOperation().intValue()==0?1:-1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE
                , JSON.toJSONString(behaviorDTO));
        log.info("消息发送成功==> 评论行为行为内容:{}",behaviorDTO);
        return ResponseResult.okResult(map);
    }
}
